package org.cosmact.designer.vxml.gefeditor.editpart;

import java.util.Collections;
import java.util.List;

import org.cosmact.designer.vxml.gefeditor.editpart.policy.DocumentXYLayoutEditPolicy;
import org.cosmact.vxml.model.Document;
import org.cosmact.vxml.model.ModelPackage;
import org.eclipse.draw2d.ConnectionLayer;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.FreeformLayer;
import org.eclipse.draw2d.FreeformLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.MarginBorder;
import org.eclipse.draw2d.ShortestPathConnectionRouter;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.LayerConstants;
import org.eclipse.gef.editpolicies.RootComponentEditPolicy;
import org.eclipse.gef.editpolicies.SnapFeedbackPolicy;

public class DocumentEditPart extends AbstractVxmlEditPart {

    private static final int SHORTEST_PATH_SPACE = 12;

    @Override
    protected IFigure createFigure() {
	Figure figure = new FreeformLayer();
	figure.setLayoutManager(new FreeformLayout());
	figure.setBorder(new MarginBorder(5));

	// Connection router(Global setting. You can set router for every
	// connection when create connection)
	setConnectionRouterOnConnectionLayer(figure);
	return figure;
    }

    private void setConnectionRouterOnConnectionLayer(Figure figure) {
	// Create the static router for the connection layer
	ConnectionLayer connLayer = (ConnectionLayer) getLayer(LayerConstants.CONNECTION_LAYER);
	ShortestPathConnectionRouter router = new ShortestPathConnectionRouter(
		figure);
	router.setSpacing(SHORTEST_PATH_SPACE);
	connLayer.setConnectionRouter(router);
    }

    @Override
    protected void createEditPolicies() {
	installEditPolicy(EditPolicy.NODE_ROLE, null);

	installEditPolicy(EditPolicy.GRAPHICAL_NODE_ROLE, null);

	installEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE, null);

	// Make this root part can't be deleted.
	installEditPolicy(EditPolicy.COMPONENT_ROLE,
		new RootComponentEditPolicy());

	installEditPolicy(EditPolicy.LAYOUT_ROLE,
		new DocumentXYLayoutEditPolicy((XYLayout) getContentPane()
			.getLayoutManager()));

	installEditPolicy("Snap Feedback", new SnapFeedbackPolicy()); //$NON-NLS-1$
    }

    @SuppressWarnings("unchecked")
    @Override
    protected List getModelChildren() {
	Object model = getModel();
	if (model instanceof Document) {
	    Document document = (Document) model;
	    return document.getDialogs();
	}
	return Collections.EMPTY_LIST;
    }

    @Override
    public void notifyChanged(Notification notification) {
	int featureId = notification.getFeatureID(ModelPackage.class);
	switch (featureId) {
	case ModelPackage.DOCUMENT__DIALOGS:
	    refreshChildren();
	    break;
	}
    }
}
